/*
 * Copyright 2017 - 2025 the original author or authors.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see [https://www.gnu.org/licenses/]
 */

package infra.web.view.freemarker;

import org.jspecify.annotations.Nullable;

import java.util.Locale;

import freemarker.template.Configuration;
import infra.util.StringUtils;
import infra.web.view.AbstractTemplateViewResolver;
import infra.web.view.AbstractUrlBasedView;
import infra.web.view.UrlBasedViewResolver;
import infra.web.view.View;

/**
 * Convenience subclass of {@link infra.web.view.UrlBasedViewResolver}
 * that supports {@link FreeMarkerView} (i.e. FreeMarker templates) and custom subclasses of it.
 *
 * <p>The view class for all views generated by this resolver can be specified
 * via the "viewClass" property. See {@code UrlBasedViewResolver} for details.
 *
 * <p><b>Note:</b> To ensure that the correct encoding is used when the rendering
 * the response, set the {@linkplain #setContentType(String) content type} with an
 * appropriate {@code charset} attribute &mdash; for example,
 * {@code "text/html;charset=UTF-8"}; however, as of Infra 5.0 it is
 * no longer strictly necessary to explicitly set the content type in the
 * {@code FreeMarkerViewResolver} if you have set an explicit encoding via either
 * {@link FreeMarkerView#setEncoding(String)},
 * {@link FreeMarkerConfigurer#setDefaultEncoding(String)}, or
 * {@link Configuration#setDefaultEncoding(String)}.
 *
 * <p><b>Note:</b> When chaining ViewResolvers, a {@code FreeMarkerViewResolver} will
 * check for the existence of the specified template resources and only return
 * a non-null {@code View} object if the template was actually found.
 *
 * @author Juergen Hoeller
 * @author <a href="https://github.com/TAKETODAY">Harry Yang</a>
 * @see #setViewClass
 * @see #setPrefix
 * @see #setSuffix
 * @see #setRequestContextAttribute
 * @see FreeMarkerView
 * @since 4.0
 */
public class FreeMarkerViewResolver extends AbstractTemplateViewResolver {

  /**
   * Sets the default {@link #setViewClass view class} to {@link #requiredViewClass}:
   * by default {@link FreeMarkerView}.
   */
  public FreeMarkerViewResolver() {
    setViewClass(requiredViewClass());
  }

  /**
   * A convenience constructor that allows for specifying {@link #setPrefix prefix}
   * and {@link #setSuffix suffix} as constructor arguments.
   *
   * @param prefix the prefix that gets prepended to view names when building a URL
   * @param suffix the suffix that gets appended to view names when building a URL
   */
  public FreeMarkerViewResolver(String prefix, String suffix) {
    this();
    setPrefix(prefix);
    setSuffix(suffix);
  }

  /**
   * Requires {@link FreeMarkerView}.
   */
  @Override
  protected Class<?> requiredViewClass() {
    return FreeMarkerView.class;
  }

  @Override
  protected AbstractUrlBasedView instantiateView() {
    return getViewClass() == FreeMarkerView.class ? new FreeMarkerView() : super.instantiateView();
  }

  /**
   * Delegates to {@code super.loadView(viewName, locale)} for standard behavior
   * and then to {@link #postProcessView(FreeMarkerView, Locale)} for customization.
   *
   * @see UrlBasedViewResolver#loadView(String, Locale)
   * @see #postProcessView(FreeMarkerView, Locale)
   * @since 5.0
   */
  @Override
  @Nullable
  protected View loadView(String viewName, Locale locale) throws Exception {
    View view = super.loadView(viewName, locale);
    if (view instanceof FreeMarkerView freeMarkerView) {
      postProcessView(freeMarkerView, locale);
    }
    return view;
  }

  /**
   * Post process the supplied {@link FreeMarkerView} after it has been {@linkplain
   * UrlBasedViewResolver#loadView(String, Locale)
   * loaded}.
   * <p>The default implementation attempts to override the
   * {@linkplain infra.web.view.AbstractView#setContentType(String)
   * content type} of the view with {@code "text/html;charset=<encoding>"},
   * where {@code <encoding>} is equal to an explicitly configured character
   * encoding for the underlying FreeMarker template file. If an explicit content
   * type has been configured for this view resolver or if no explicit character
   * encoding has been configured for the template file, this method does not
   * modify the supplied {@code FreeMarkerView}.
   *
   * @param locale the Locale to retrieve the view for
   * @see #loadView(String, Locale)
   * @see #setContentType(String)
   * @see infra.web.view.AbstractView#setContentType(String)
   * @since 5.0
   */
  protected void postProcessView(FreeMarkerView freeMarkerView, Locale locale) {
    // If an explicit content type has been configured for all views, it has
    // already been set in the view in UrlBasedViewResolver#buildView(String),
    // and there is no need to override it here.
    if (getContentType() != null) {
      return;
    }

    // Check if the view has an explicit encoding set.
    String encoding = freeMarkerView.getEncoding();
    if (encoding == null) {
      // If an explicit encoding has not been configured for this particular view,
      // use the explicit default encoding for the FreeMarker Configuration, if set.
      Configuration configuration = freeMarkerView.obtainConfiguration();
      if (configuration.isDefaultEncodingExplicitlySet()) {
        encoding = configuration.getDefaultEncoding();
      }
    }
    if (StringUtils.hasText(encoding)) {
      String contentType = "text/html;charset=" + encoding;
      if (logger.isDebugEnabled()) {
        logger.debug("Setting Content-Type for view [%s] to: %s".formatted(freeMarkerView, contentType));
      }
      freeMarkerView.setContentType(contentType);
    }

    if (freeMarkerView.getLocale() == null) {
      freeMarkerView.setLocale(locale);
    }
  }
}
